import { Suspense, lazy } from "react";
import { CircleLoading } from "@/components/loading";

interface DynamicComponentProps {
	path: string;
}

const ENTRY_PATH = "/src/pages";
const PAGES = import.meta.glob("/src/pages/**/*.tsx");

export const DynamicComponent = ({ path }: DynamicComponentProps) => {
	const fullPath = path.startsWith("/") ? `${ENTRY_PATH}${path}` : path;
	const Component = lazy(() => {
		const module = PAGES[fullPath];
		if (!module) {
			console.error("Module not found:", fullPath);
			console.log("Available paths:", Object.keys(PAGES));
			return Promise.reject(new Error(`Module not found: ${fullPath}`));
		}
		return module();
	});

	return (
		<Suspense fallback={<CircleLoading />}>
			<Component />
		</Suspense>
	);
};
